// 文件名：cpp_string_demo.cpp
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <map>
#include <cctype>
#include <ctime>

using namespace std;

// 1. 统计词频
map<string, int> count_word_frequency(const string& text) {
    map<string, int> frequency;
    istringstream iss(text);
    string word;
    
    while (iss >> word) {
        // 移除标点并转为小写
        word.erase(remove_if(word.begin(), word.end(), ::ispunct), word.end());
        transform(word.begin(), word.end(), word.begin(), ::tolower);
        
        if (!word.empty()) {
            frequency[word]++;
        }
    }
    
    return frequency;
}

// 2. 凯撒密码加密
string caesar_cipher(string text, int shift) {
    for (char &c : text) {
        if (isalpha(c)) {
            char base = isupper(c) ? 'A' : 'a';
            c = ((c - base + shift) % 26) + base;
        }
    }
    return text;
}

int main() {
    // 案例1：统计词频
    string sample_text = "This is a sample text. Sample text is used for testing.";
    cout << "原文: " << sample_text << endl;
    
    auto word_freq = count_word_frequency(sample_text);
    cout << "\n词频统计:\n";
    for (const auto& [word, count] : word_freq) {
        cout << word << ": " << count << endl;
    }
    
    // 案例2：凯撒密码
    string secret = "Hello, World!";
    int shift = 5;
    
    string encrypted = caesar_cipher(secret, shift);
    string decrypted = caesar_cipher(encrypted, -shift);
    
    cout << "\n凯撒密码 (移位=" << shift << "):\n";
    cout << "原文: " << secret << endl;
    cout << "加密: " << encrypted << endl;
    cout << "解密: " << decrypted << endl;
    
    // 性能对比
    cout << "\n字符串连接性能对比:\n";
    const int iterations = 10000;
    
    // 方法1：+= 操作符
    clock_t start = clock();
    string s1;
    for (int i = 0; i < iterations; ++i) {
        s1 += "a";
    }
    cout << "+= 用时: " << (clock() - start) << " ms" << endl;
    
    // 方法2：stringstream
    start = clock();
    ostringstream oss;
    for (int i = 0; i < iterations; ++i) {
        oss << "a";
    }
    string s2 = oss.str();
    cout << "stringstream 用时: " << (clock() - start) << " ms" << endl;
    
    return 0;
}